<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数组方法2</title>
    <script>
        //flat将数组中的数组展开，默认只展开一层，写几展开几层，infinity将数组内的数组全部展开
        const arr1 = [0, 1, 2, [3, 4]];
        console.log(arr1.flat());
        const arr2 = [0, 1, [2, [3, [4, 5]]]];
        console.log(arr2.flat());
        console.log(arr2.flat(2));
        console.log(arr2.flat(Infinity));

        //flatMap将数组每个值放入，函数返回值赋值给当前数值下标所在位置
        const arr3 = [2, 2, 1];
        const result = arr3.flatMap((num) => (num === 2 ? [2, 2] : 1));
        console.log(result);

        //forEach输出每个值
        const array1 = ['a', 'b', 'c'];
        array1.forEach((element) => console.log(element));

        //includes看数组是否有这个值
        const pets = ['cat', 'dog', 'bat'];
        console.log(pets.includes('cat'));

        //indexOf找数组中对应值的下标，
        //('bison')从开始查找，('bison', 2)从下标2开始找，若未找到返回-1
        const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
        console.log(beasts.indexOf('bison'));
        console.log(beasts.indexOf('bison', 2));
        console.log(beasts.indexOf('giraffe'));

        //join改变数组值之间间隔，并合并为一个，默认情况下间隔改为逗号
        const elements = ['Fire', 'Air', 'Water'];
        console.log(elements.join());
        console.log(elements.join(''));
        console.log(elements.join('-'));

        //keys保存数组下标
        const array2 = ['a', 'b', 'c'];
        const iterator = array2.keys();
        for (const key of iterator) {
            console.log(key);
        }

        //lastIndexOf返回对应值在数组中最后一次出现下标
        const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];
        console.log(animals.lastIndexOf('Dodo'));
        console.log(animals.lastIndexOf('Tiger'));

        //map存储对应数值所在地址
        const array3 = [1, 4, 9, 16];
        const map1 = array1.map((x) => x * 2);
        console.log(map1);

        //pop将数组最后一个值返回并删去
        const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
        console.log(plants.pop());
        console.log(plants);
        plants.pop();
        console.log(plants);

        //push将值加到数组最后一位，并返回数组个数
        const animals2 = ['pigs', 'goats', 'sheep'];
        const count = animals2.push('cows');
        console.log(count);  
        console.log(animals2);
        animals.push('chickens', 'cats', 'dogs');
        console.log(animals2);
    

    </script>
</head>

<body>

</body>

</html>